package com.htg.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;


public class DialogError {

    private Context cxt;

    private AlertDialog alertDialog = null;
    private int colorPrimary;
    private float cornerRadius;

    public DialogError(Context cxt) {
        this.cxt = cxt;
        colorPrimary = cxt.getResources().getColor(R.color.blue_0166FF, cxt.getTheme());
        cornerRadius = cxt.getResources().getDimensionPixelSize(R.dimen.dp_5);
    }

    public void show(String content) {
        if (alertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(cxt);
            alertDialog = builder.create();
        } else {
            if (alertDialog.isShowing()) {
                return;
            }
        }
        alertDialog.show();
        View view = LayoutInflater.from(cxt).inflate(R.layout.dialog_error, null);
        Window window = alertDialog.getWindow();
        window.setBackgroundDrawableResource(R.drawable.shape_white_rounded_12dp);
        WindowManager.LayoutParams params = window.getAttributes();
        int width = cxt.getResources().getDimensionPixelSize(R.dimen.dp_280);

        params.width = width;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        // 创建一个 GradientDrawable 对象
        GradientDrawable drawableRoot = new GradientDrawable();
        drawableRoot.setShape(GradientDrawable.RECTANGLE);
        drawableRoot.setColor(cxt.getResources().getColor(R.color.white, cxt.getTheme())); // 设置背景颜色
        drawableRoot.setCornerRadius(cornerRadius);// 设置圆角半径
        window.setBackgroundDrawable(drawableRoot);
        window.setContentView(view);

        TextView tvContent = view.findViewById(R.id.tv_dialog_error_content);
        TextView tvOk = view.findViewById(R.id.tv_dialog_error_ok);
        tvOk.setTextColor(colorPrimary);

        tvContent.setText(content);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

    }

    public void dismis() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        alertDialog = null;
    }

    public void setColorPrimary(int colorPrimary) {
        this.colorPrimary = colorPrimary;
    }

    public void setCornerRadius(float cornerRadius) {
        this.cornerRadius = cornerRadius;
    }
}
